<?php

namespace app\api\controller\Course;

use app\api\controller\Common;
use app\api\Logic\Campusclass\CampusClassLogic;
use app\api\Logic\Course\MallGoodsLogic;
use app\api\Logic\Course\ManagementOrderLogic;
use app\api\Logic\Pay\PayLogic;
use app\api\model\CampusCourseOrderModel;
use app\api\model\CampusCourseOrderSublevelModel;
use think\Db;
use think\Exception;

/**
 * 专项课订单接口
 */
class ManagementOrder extends Common
{
    protected $noNeedLogin = ['*'];

    protected $mallGoodsLogic;
    protected $managementOrderLogic;
    protected $payLogic;
    protected $campusClassLogic;

    public function _initialize()
    {
        parent::_initialize();
        $this->mallGoodsLogic = new MallGoodsLogic();
        $this->managementOrderLogic = new ManagementOrderLogic();
        $this->payLogic = new PayLogic();
        $this->campusClassLogic = new CampusClassLogic();
    }

    /**
     * 课时类型
     * @return array[]
     */
    public function classHourTypeMap(){
        return [
            'hour'      => ['type' => 'hour', 'name' => '课时'],
            'monthly'   => ['type' => 'monthly', 'name' => '月'],
            'day'       => ['type' => 'day', 'name' => '日']
        ];
    }

    /**
     * 供前端调用，返回课时类型
     */
    public function classHourTypeAry(){
        $list = array_values($this->classHourTypeMap());
        if (!empty($list)) {
            $this->success('查询成功', $list);
        }
        $this->error('暂无数据');
    }

    /**
     * 订单整理
     */
    public function collation(){
        if($this->request->isPost()){
            $param = $this->request->param();
            //验证数据
            $param = $this->verifyData($param);

            $mallGoodsId = $param['mall_goods_id'] ?? 0;
            if(empty($mallGoodsId)){
                $this->error('选课ID必须');
            }

            //课时类型
            $classHourType = $param['class_hour_type'] ?? '';
            if(empty($classHourType)){
                $this->error('请选择课时类型');
            }
            if(!isset($this->classHourTypeMap()[$classHourType])){
                $this->error('课时类型不存在');
            }

            //课时id
            if(!isset($param['class_hour_id'])){
                $this->error('课时ID必须');
            }
            $classHourId = $param['class_hour_id'];

            //获取选课详情
            $info = $this->mallGoodsLogic->info($param['shop_id'],$mallGoodsId);
            if(empty($info)){
                $this->error('信息不存在');
            }

            //若选课不为课程类型，则提示异常，该接口仅给课程订单调用
            if($info['type'] != 1){
                $this->error('接口调用错误');
            }

            if(!isset($info[$classHourType]) || empty($info[$classHourType])){
                $this->error('所选课时为空或不存在');
            }

            //返回前端价格信息
            $info['price_info'] = [
                'unit_price' => 0,//单价
                'unit' => '',//课时类型
                'total_price' => 0,//总价
                'num' => 0,//数量
            ];
            foreach ($info[$classHourType] as $val){
                if($val['id'] == $classHourId){
                    $info['price_info']['unit_price'] = $val['price'];
                    $info['price_info']['unit'] = $this->classHourTypeMap()[$classHourType]['name'];
                    $info['price_info']['total_price'] = $val['total_price'];
                    $info['price_info']['num'] = $val['num'];
                }
            }

            $info['class_hour_type'] = $classHourType;

            //可选班级列表，根据课程获取班级列表，再根据班级的is_choose判断是否可选
            $classList = $this->campusClassLogic->getClassByCourseIds($param['shop_id'],[$info['c_id']]);
            if(!empty($classList)){
                foreach ($classList as $classInfo){
                    if($classInfo['is_choose'] == 1){
                        $info['class_list'][] = $classInfo;
                    }
                }
            }

            //todo 本次可使用优惠券信息，暂未实现该接口，默认空数组
            $info['coupon_info'] = [];

            if(!empty($info)){
                $this->success('查询成功',$info);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 创建订单
     */
    public function create(){
        if($this->request->isPost()){
            $param = $this->request->param();
            //验证数据
            $param = $this->verifyData($param);

            $mallGoodsId = $param['mall_goods_id'] ?? 0;
            if(empty($mallGoodsId)){
                $this->error('选课ID必须');
            }

            if(!isset($param['pay_type']) || !isset($this->payTypeMap()[$param['pay_type']])){
                $this->error('支付方式不可用');
            }

            //课时类型
            $classHourType = $param['class_hour_type'] ?? '';
            if(empty($classHourType)){
                $this->error('请选择课时类型');
            }
            if(!isset($this->classHourTypeMap()[$classHourType])){
                $this->error('课时类型不存在');
            }

            //课时id
            if(!isset($param['class_hour_id'])){
                $this->error('课时ID必须');
            }
            $classHourId = $param['class_hour_id'];

            //获取选课详情
            $info = $this->mallGoodsLogic->info($param['shop_id'],$mallGoodsId);
            if(empty($info)){
                $this->error('信息不存在');
            }

            //若选课不为课程类型，则提示异常，该接口仅给课程订单调用
            if($info['type'] != 1){
                $this->error('接口调用错误');
            }

            if(!isset($info[$classHourType]) || empty($info[$classHourType])){
                $this->error('所选课时为空或不存在');
            }

            //根据所选课时类型和id返回相应价格信息
            foreach ($info[$classHourType] as $val){
                if($val['id'] == $classHourId){
                    $info['price_info']['unit_price'] = $val['price'];
                    $info['price_info']['unit'] = $this->classHourTypeMap()[$classHourType]['name'];
                    $info['price_info']['total_price'] = $val['total_price'];
                    $info['price_info']['num'] = $val['num'];
                }
            }
            if(!isset($info['price_info'])){
                $this->error('课时信息错误');
            }

            Db::startTrans();
            try {
                $orderInfo = [
                    'no' => date("YmdHis") . mt_rand(100000, 999999),
                    'shop_id' => $param['shop_id'],
                    'user_id' => $param['user_id'],
                    'style' => 1,
                    'goods_id' => $mallGoodsId,
                    'price' => $info['price_info']['total_price'],
                    'name' => $info['name'],
                    'image' => $info['image'],
                    'status' => 1,
                    'createtime' => time()
                ];

                $orderId = CampusCourseOrderModel::insertGetId($orderInfo);

                //生成订单子项
                $givingNum = 0; //todo 赠送课时数
                $givingType = ''; //todo 赠送课时类型
                $allNum = $info['price_info']['num'] + $givingNum; //总课时数
                $orderSublevelData = [
                    'no' => $orderInfo['no'],
                    'shop_id' => $param['shop_id'],
                    'user_id' => $param['user_id'],
                    'type' => 3,
                    'gs_id' => $info['c_id'],
                    'm_type' => $classHourType,
                    'm_type_num' => $info['price_info']['num'] ?? 0,
                    'num' => 1,
                    'price' => $info['price_info']['total_price'],
                    'giving' => $givingNum,
                    'giving_type' => $givingType,
                    'all_num' => $allNum,
                    'use_num' => 0,
                    'status' => 0,  //未支付成功状态都为0
                    'class_ids' => $param['class_id'] ?? 0  //所选班级
                ];
                CampusCourseOrderSublevelModel::insert($orderSublevelData);

                //订单金额
                $orderMoney = $info['price_info']['total_price'];
                //优惠金额
                $discountMoney = $param['coupon_amount'] ?? 0;
                //实付金额 = 订单金额 - 优惠券抵扣金额
                $payMoney = round($orderMoney - $discountMoney,2);

                //创建主订单记录
                $this->payLogic->createOrder([
                    'shop_id' => $param['shop_id'],
                    'controller' => 'course/management_order',
                    'order_sn' => $orderInfo['no'],
                    'order_id' => $orderId,
                    'user_id' => $param['user_id'],
                    'price' => $orderMoney,
                    'coupon_id' => $param['coupon_id'] ?? 0,
                    'coupon_amount' => $discountMoney,
                    'pay_type' => $param['pay_type'] == 1 ? 'wechat' : ($param['pay_type'] == 2 ? 'alipay' : ''),
                    'real_price' => $payMoney,
                    'pay_amount' => $payMoney,
                    'status' => 0,
                    'createtime' => time()
                ]);

                //如果课程价格为0，则直接支付成功
                $payStatus = 1; //待支付
                if($payMoney == 0){
                    //执行支付成功回调
                    $res = $this->managementOrderLogic->payment(
                        [
                            'out_trade_no' => $orderInfo['no']
                        ]
                    );
                    if($res){
                        $payStatus = 2; //已支付
                    }
                }

                Db::commit();
                $this->success('下单成功',['order_id' => $orderId,'pay_status' => $payStatus]);
            }catch (Exception $e){
                Db::rollback();
                throw $e;
            }
            $this->error('下单失败');
        }
        $this->error('请求错误');
    }

    /**
     * 微信支付回调
     * todo 需按实际情况修改
     */
    public function notify(){
        //todo 默认写法，需按实际情况修改
        $xmlInfo = file_get_contents("php://input");
        //xms转数组
        $notifyRes = $this->xmlToArray($xmlInfo);

        //todo 回调数据验签成功
        if(true){
            $res = $this->managementOrderLogic->payment($notifyRes);
            if($res){
                echo 'success';
                exit;
            }
        }
        echo 'fail';
    }

    /**
     * 主订单支付回调,用于订单商品价格为0直接支付
     */
    public function pay_result(){
        $params = $this->request->param();

        $orderId = $params['order_id'] ?? 0;
        if(empty($orderId)){
            return false;
        }

        return $this->managementOrderLogic->payLogNotify($orderId);
    }

    /**
     * 我的专项课
     */
    public function orderList(){
        if($this->request->isPost()){
            $param = $this->request->param();
            //验证数据
            $param = $this->verifyData($param);

            //获取我的专项课课程列表
            $list = $this->managementOrderLogic->orderList($param,true);

            if(!empty($list)){
                $this->success('查询成功',$list);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }
}
